<script setup>
import {ref, reactive, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus'; // 使用 Element Plus 的 message 组件
import axios from 'axios'
import {userStore} from '@/store/index.js'

const userItemStore = userStore();
const router = useRouter();


//======================================手机登录===========================================
const refSmsForm = ref(null);
const smsForm = reactive({
  telephone: '',
  code: ''
});

const rulesPhone = reactive({
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
})

const smsDisabled = ref(false);  //发短信按钮是否可用
const smsText =ref('发送短信验证码');

const activeName =ref('userName');
//获取短信
const sendSms = ()=>{
  //验证手机号是否正确
  refSmsForm.value.validateField('telephone', error => {
    //如果没有错误，则验证通过
    if (error) {
      smsDisabled.value = true;
      axios.get(`/user/sendSms/${smsForm.telephone}`).then(resp => {
        //发送成功
        ElMessage({message:resp.data,type:'success'});
      }).catch(error => {
        //发送失败
        ElMessage.error(error.response.data);
      }).finally(() => {
        //按钮文字变成倒计时
        let seconds = 15;
        smsText.value = `${seconds}秒后重新发送`;
        let timer = setInterval(() => {
          seconds--;
          if (seconds > 0) {
            smsText.value = `${seconds}秒后重新发送`;
          } else {
            //修改文字
            smsText.value = "发送短信验证码";
            //按钮可用
            smsDisabled.value = false;
            //清除定时器
            clearInterval(timer);
          }
        }, 1000);
      });
    }
  });
}
//手机登录按钮
const smsLogin = () => {
  refSmsForm.value.validate(valid => {
    if (valid) {
      axios.post('/user/smsLogin', smsForm).then(resp => {
        const user = resp.data;
        //保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('token', user.token);
        //修改保存的用户信息
        userItemStore.updateUser(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        //提示登录成功
        ElMessage({message: `登录成功，欢迎您：${user.customerName}！`, type: 'success'});
        //跳转到首页
        router.push('/');
      }).catch(error => {
        //登录失败
        ElMessage.error('登录失败' + error.response.data);
      });
    } else {
      return false;
    }
  })
}



onMounted(() => {

})


</script>
<template>
  <div class="login-container">
    <el-card class="card">
      <h2 class="title">蜗牛充电桩用户登录</h2>
      <el-tabs v-model="activeName" type="border-card">
          <el-form ref="refSmsForm" :model="smsForm"
                   class="login-form" :rules="rulesPhone"
                   label-position="left"
                   label-width="80px" >
            <el-form-item label="手机号：" prop="telephone" style="margin-top: 20px">
              <el-input v-model="smsForm.telephone"
                        placeholder="请输入手机号">
                <template #suffix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="smsForm.code" maxlength="4"
                          minlength="4" placeholder="验证码"
                          style="width: 90px; margin-right: 10px;">
                </el-input>
                <el-button type="text" :disabled="smsDisabled"
                           @click="sendSms">
                  <el-icon :size="20"><Message /></el-icon>
                  {{smsText }}
                </el-button>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;"
                         type="primary" @click="smsLogin"
                         icon="el-icon-user-solid">登录
              </el-button>
            </div>
          </el-form>
      </el-tabs>


    </el-card>
  </div>
</template>


<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
  display: flex;
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  height: 100%;
}

.card {
  margin-top: 20px;
  width: 450px;
  height: 430px;
  padding: 15px;
}

.title {
  margin-top: 10px;
  font-size: 25px;
  text-shadow: 2px 2px 4px #888;
  text-align: center;
}

.login-form {
  max-width: 300px;
  margin: 0 auto;
}

.login-btn-container {
  text-align: center;
  margin-bottom: 30px;
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
</style>